package com.linkcard.list.persistence;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.linkcard.commen.tools.Page;
import com.linkcard.list.model.Category;

public class CategoryDaoImpl extends HibernateDaoSupport implements CategoryDao {

	//添加类别
	public boolean addCategory(Category category) {
		try
		{
		this.getHibernateTemplate().save(category);
		}catch(Exception e)
		{
			e.printStackTrace();
			return false;
		}
		return true;
	}

	//获得类别列表
	public List categoryList(final Integer columnId,final int pid) {
		List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session session)throws HibernateException, SQLException {
				Criteria criteria=session.createCriteria(Category.class);
				         criteria.add(Expression.eq("columnId", columnId));
				         criteria.add(Expression.eq("pid",pid));
				         criteria.addOrder(Order.asc("sort"));
				return criteria.list();
			}
		});
		return list;
	}

	//修改类别
	public boolean modifyCategory(Category category) {
		try
		{
		Category c=(Category)this.getHibernateTemplate().get(Category.class, category.getId());
		c.setName(category.getName());
		c.setSort(category.getSort());
		this.getHibernateTemplate().update(c);
		}catch(Exception e)
		{
			e.printStackTrace();
			return false;
		}
		return true;
	}

	//删除类别
	public boolean deleteCategory(Category category) {
        try
        {
        	Category c=(Category)this.getHibernateTemplate().get(Category.class, category.getId());
        	this.getHibernateTemplate().delete(c);
        }catch(Exception e)
        {
        	e.printStackTrace();
        	return false;
        }
		return true;
	}

	//查找类别
	public Category findCategory(Integer categoryId) {
		try
		{
			Category category=(Category)this.getHibernateTemplate().get(Category.class, categoryId);
			return category;
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

}
